package com.tianyang.yukuaifu.business.main.presenter;

import com.alibaba.fastjson.JSONObject;
import com.tianyang.yukuaifu.business.main.contract.BindCodePlateContract;
import com.tianyang.yukuaifu.business.main.model.MainModel;
import com.tianyang.yukuaifu.jump.eventbus.RefreshDeviceEvent;
import com.tianyang.yukuaifu.utils.IntentTool;
import com.tianyang.yukuaifu.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;

import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Description：绑定码牌
 * Created by xyj on 2024/3/21
 */
public class BindCodePlatePresenter implements BindCodePlateContract.Presenter {

    private BindCodePlateContract.View mView;

    private CompositeSubscription mSubscription;

    private String deviceType;

    public BindCodePlatePresenter(BindCodePlateContract.View mView, String deviceType) {
        this.mView = mView;
        this.deviceType = deviceType;
        mSubscription = new CompositeSubscription();
    }

    @Override
    public void confirmPosBind(String sn) {
        mView.showLoadingDialog(false);
        Subscription subscription = MainModel.getInstance().bindingDevice(deviceType, sn)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<JSONObject>() {
                    @Override
                    public void onCompleted() {
                        mView.dismissLoadingDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.dismissLoadingDialog();
                        mView.showErrorText(e);
                    }

                    @Override
                    public void onNext(JSONObject output) {
                        ToastUtil.show("新增成功");
                        EventBus.getDefault().post(new RefreshDeviceEvent(true));
                        IntentTool.finishActivity(mView.getContext());
                    }
                });
        mSubscription.add(subscription);
    }

    @Override
    public void onDestroyPresenter() {
        if (mSubscription != null && !mSubscription.isUnsubscribed()) {
            mSubscription.unsubscribe();
            mSubscription = null;
        }
        if (mView != null) {
            mView = null;
        }
    }
}
